package com.minhua.jijiehao2.utils;

import com.minhua.jijiehao2.base.BaseApplication;

import java.io.File;

/**
 * @author moo
 * @date 2018/1/4.
 * @describe
 */
public class FileUtils {

    /**
     * 获取存储根目录
     */
    public static File getRootSaveFile() {
        File rootFile = BaseApplication.Companion.getAPP().getExternalFilesDir(null);
        if (!rootFile.exists()) {
            rootFile.mkdirs();
        }
        return rootFile;
    }

    /**
     * 获取缓存根目录
     */
    public static File getRootCatchFile() {
        File rootFile = BaseApplication.Companion.getAPP().getExternalCacheDir();
        if (!rootFile.exists()) {
            rootFile.mkdirs();
        }
        return rootFile;
    }


    public static File getSaveFileDir(String path) {
        File bookFile;
        bookFile = new File(getRootSaveFile().getAbsolutePath() + File.separator + path);
        if (!bookFile.exists()) {
            bookFile.mkdirs();
        }
        return bookFile;
    }

    public static File getCatchFileDir(String path) {
        File bookFile;
        bookFile = new File(getRootCatchFile().getAbsolutePath() + File.separator + path);
        if (!bookFile.exists()) {
            bookFile.mkdirs();
        }
        return bookFile;
    }


    public static void deleteFile(File file) {
        if (file == null || !file.exists())
            return;
        if (file.isFile()) {
            file.delete();
        } else {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                deleteFile(files[i]);
            }
            file.delete();
        }
    }

    public static void deleteFile(String path) {
        File file = new File(path);
        deleteFile(file);
    }

    public static long getFileSize(File file) {
        long size = 0;
        if (file == null || !file.exists())
            return size;
        if (file.isFile()) {
            size += file.length();
        } else {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                size += getFileSize(files[i]);
            }
        }
        return size;
    }

    public static long getFileSize(String path) {
        File file = new File(path);
        return getFileSize(file);
    }

    public static String getFileMString(long size) {
        if (size == 0) {
            return "0.00M";
        } else {

            double mSize = (double) size / (1024 * 1024);
            return String.format("%.2f", mSize) + "M";
        }
    }
}